/*
 * @Author: wwssaabb
 * @Date: 2021-11-23 08:42:09
 * @LastEditTime: 2021-12-11 17:58:52
 * @FilePath: \handwritten-code\array\map.js
 */

//实现map

function myMap(arr, fn) {
  let result = []
  if (!Array.isArray(arr) || !arr.length || typeof fn !== 'function') {
    return result
  } else {
    for (let i = 0; i < arr.length; i++) {
      result.push(fn(arr[i], i, arr))
    }
    return result
  }
}

//array.prototype 调用

Array.prototype.myMap = function (fn) {
  if (typeof fn !== 'function') return new TypeError(fn + ' is not a function')
  let result = []
  let arr = this
  return arr.length === 0 ?
    result :
    (function () {
      for (let i = 0; i < arr.length; i++) {
        result.push(fn(arr[i], i, arr))
      }
      return result
    })()
}

Function.prototype.myMap = function (executor, thisArg = globalThis) {
  //this判断
  if (this == null) return new TypeError('this is null or undefined')
  //回调函数判断类型判断
  if (typeof executor !== 'function') return new TypeError(executor + ' is no a function')

  let res = []
  for (let i = 0; i < this.length; i++) {
    res.push(executor.call(thisArg, this[i], i, this))
  }
  return res
}

let a = [{
  a: 1
}, {
  b: 2
}, {
  c: 3
}, {
  d: 4
}, 1, 2, 'a']

// let b = myMap(a, i => i)

// console.log(a)
console.log(a.myMap(i => i))
console.log(a.map(i => i))
console.log([].myMap(i => i))
console.log([].map(i => i))